package hu.codelab.lg.servicecenter.activity;

import hu.codelab.lg.servicecenter.R;
import hu.codelab.lg.servicecenter.ServiceCenterApplication;
import hu.codelab.lg.servicecenter.entities.ServiceCenter;
import hu.codelab.lg.servicecenter.entities.ServiceCenters;
import hu.codelab.lg.servicecenter.helpers.MyLocationManager;
import hu.codelab.lg.servicecenter.helpers.MyLocationManager.LocationResult;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bugsense.trace.BugSenseHandler;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public final class LGMapActivity extends MapActivity {
    
    private RelativeLayout relativeLayout;
    private Drawable drawable;
    private LGItemizedOverlay itemizedOverlay;
    
    protected int globalindex;
    protected String myProvider;
    
    protected MapView map;
    protected ImageView closeBubbleImage;
    protected Typeface font;
    protected ServiceCenters serviceCenters;
    protected MapController mapController;
    protected List<ServiceCenter> centers;
    protected List<Overlay> mapOverlays;
    protected PositionItemizedOverlay pio;
    protected Handler handler;
    
    protected MyLocationManager myLocationManager = new MyLocationManager();
    
    @Override
    protected void onCreate(final Bundle icicle) {
        super.onCreate(icicle);
        
        BugSenseHandler.setup(this, getString(R.string.BUGSENSE_API_KEY));
        
        handler = new Handler();
        
        // getting font resources
        final Resources resources = getResources();
        font = Typeface.createFromAsset(getAssets(), "helvetica_neue.ttf");
        
        // inflating the layout
        relativeLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_map, null);
        setContentView(relativeLayout);
        
        final TextView leadView = (TextView) relativeLayout.findViewById(R.id.tv_header_lg);
        final TextView titleView = (TextView) relativeLayout.findViewById(R.id.tv_header_view);
        
        leadView.setTypeface(font);
        titleView.setTypeface(font);
        
        // initializing the mapview
        map = (MapView) relativeLayout.findViewById(R.id.mv_map);
        map.setBuiltInZoomControls(true);
        
        // setting center to budapest
        mapController = map.getController();
        mapController.setCenter(new GeoPoint(47495000, 19050000));
        mapController.setZoom(7);
        
        mapOverlays = map.getOverlays();
        drawable = this.getResources().getDrawable(R.drawable.icon_location);
        itemizedOverlay = new LGItemizedOverlay(drawable);
        
        // adding required overlays
        if (((ServiceCenterApplication) getApplication()).getCurrentServiceCenter() != null) {
            centers = new ArrayList<ServiceCenter>();
            centers.add(((ServiceCenterApplication) getApplication()).getCurrentServiceCenter());
        } else {
            serviceCenters = ((ServiceCenterApplication) getApplication()).getOfflineServiceCenters();
            
            if (serviceCenters == null || serviceCenters.getServiceCenters() == null || serviceCenters.getServiceCenters().isEmpty()) {
                return;
            }
            centers = serviceCenters.getServiceCenters();
        }
        
        GeoPoint point;
        OverlayItem overlayItem;
        for (ServiceCenter serviceCenter : centers) {
            point = new GeoPoint(serviceCenter.getAddress().getLatitude(), serviceCenter.getAddress().getLongitude());
            overlayItem = new OverlayItem(point, "", "");
            itemizedOverlay.addOverlay(overlayItem);
        }
        
        // starting user locating
        boolean locationAcquireable = myLocationManager.getLocation(this, locationResult);
        if (!locationAcquireable)
            Toast.makeText(LGMapActivity.this, "A pozicionálás nincs engedélyezve. Ezt a Beállítások menü Hely és biztonság pontjában tudja megtenni.", Toast.LENGTH_LONG).show();
        
        Drawable d = this.getResources().getDrawable(R.drawable.position_icon);
        pio = new PositionItemizedOverlay(d);
        
        mapOverlays.add(itemizedOverlay);
        
        // inflating the header
        final TextView headerView = (TextView) relativeLayout.findViewById(R.id.tv_header_view);
        headerView.setTypeface(font);
        try {
            headerView.setText(resources.getString(getPackageManager().getActivityInfo(getComponentName(), 0).labelRes));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public LocationResult locationResult = new LocationResult() {
        
        @Override
        public void gotLocation(Location location) {
            if (location != null) {
                GeoPoint gg = new GeoPoint((int) (location.getLatitude() * 1000000), (int) (location.getLongitude() * 1000000));
                OverlayItem oi = new OverlayItem(gg, "", "");
                pio.setPosition(oi);
                mapOverlays.add(pio);
                map.invalidate();
            } else {
                handler.post(new Runnable() {
                    
                    @Override
                    public void run() {
                        Toast.makeText(LGMapActivity.this, "A tartózkodási hely nem elérhető.", Toast.LENGTH_LONG).show();
                    }
                    
                });
                
            }
        }
        
    };
    
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
    
    public class PositionItemizedOverlay extends ItemizedOverlay<OverlayItem> {
        
        private ArrayList<OverlayItem> positionOverlayItem = new ArrayList<OverlayItem>();
        
        public PositionItemizedOverlay(Drawable defaultMarker) {
            super(boundCenterBottom(defaultMarker));
        }
        
        public void setPosition(OverlayItem item) {
            positionOverlayItem.clear();
            positionOverlayItem.add(item);
            populate();
        }
        
        @Override
        protected OverlayItem createItem(int i) {
            return positionOverlayItem.get(i);
        }
        
        @Override
        public int size() {
            return positionOverlayItem.size();
        }
        
        @Override
        public void draw(Canvas canvas, MapView mapView, boolean shadow) {
            if (!shadow) {
                super.draw(canvas, mapView, false);
            }
        }
        
    }
    
    public final class LGItemizedOverlay extends ItemizedOverlay<OverlayItem> {
        
        private ArrayList<OverlayItem> overlays = new ArrayList<OverlayItem>();
        protected View bubble;
        private ViewGroup parentBubble;
        private OverlayItem item;
        protected int currentIndex;
        private TextView titleText, addressText, moreText;
        
        public LGItemizedOverlay(final Drawable defaultMarker) {
            super(boundCenterBottom(defaultMarker));
            currentIndex = -1;
        }
        
        public void addOverlay(final OverlayItem overlay) {
            overlays.add(overlay);
            populate();
        }
        
        @Override
        public int size() {
            return overlays.size();
        }
        
        @Override
        protected OverlayItem createItem(final int i) {
            return overlays.get(i);
        }
        
        @Override
        public void draw(final Canvas canvas, final MapView mapView, final boolean shadow) {
            if (!shadow) {
                super.draw(canvas, mapView, false);
            }
        }
        
        @Override
        protected boolean onTap(int index) {
            item = overlays.get(index);
            globalindex = index;
            GeoPoint geo = item.getPoint();
            mapController.animateTo(geo);
            addBubble(geo, index);
            return true;
        }
        
        private void addBubble(GeoPoint point, int index) {
            if (bubble == null)
                initBubble();
            if (index != currentIndex) {
                map.removeView(bubble);
                currentIndex = index;
                int offsetY = -32;
                final float w = getResources().getDisplayMetrics().widthPixels;
                if (w == 240.0f)
                    offsetY = -15;
                if (w == 320.0f)
                    offsetY = -20;
                MapView.LayoutParams mvlp = new MapView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, point, 0, offsetY, MapView.LayoutParams.BOTTOM_CENTER);
                titleText.setText(centers.get(index).getName());
                addressText.setText(centers.get(index).getAddress().getReadableAddress());
                map.addView(bubble, mvlp);
            }
        }
        
        @SuppressWarnings("unused")
        public void back(final View view) {
            finish();
        }
        
        public void initBubble() {
            parentBubble = (ViewGroup) map.getParent();
            bubble = getLayoutInflater().inflate(R.layout.bubble, parentBubble, false);
            
            closeBubbleImage = (ImageView) bubble.findViewById(R.id.iv_bubble_close);
            closeBubbleImage.setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    map.removeView(bubble);
                    currentIndex = -1;
                }
                
            });
            
            titleText = (TextView) bubble.findViewById(R.id.tv_bubble_servicename);
            titleText.setTypeface(font);
            
            addressText = (TextView) bubble.findViewById(R.id.tv_bubble_serviceaddress);
            addressText.setTypeface(font);
            
            moreText = (TextView) bubble.findViewById(R.id.tv_bubble_more);
            moreText.setTypeface(font);
            moreText.setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(final View view) {
                    final Intent intent = new Intent(LGMapActivity.this, DetailedActivity.class);
                    ((ServiceCenterApplication) getApplication()).setCurrentServiceCenter(centers.get(globalindex));
                    startActivity(intent);
                }
                
            });
        }
        
    }
    
    @SuppressWarnings("unused")
    public void back(final View view) {
        finish();
    }
    
    @SuppressWarnings("unused")
    public void mainView(final View view) {
        startActivity(new Intent(getBaseContext(), MainActivity.class));
    }
    
}
